﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.StsAdmin;
using Microsoft.SharePoint;
using System.Collections.Specialized;

namespace Macaw.Moss2007.QuickDeployEnhancements
{
    public class QuickDeployProperty : ISPStsadmCommand
    {
        public string GetHelpMessage(string command)
        {
            return "-url <full url to a site in SharePoint>\r\n" +
                "-clear (flag to clear the property)";
        }

        public int Run(string command, StringDictionary keyValues, out string output)
        {
            command = command.ToLowerInvariant();
            output = null;
            switch (command)
            {
                case "quickdeployproperty":
                    return this.DoQuickDeployProperty(keyValues, out output);

                default:
                    throw new InvalidOperationException();
            }
        }

        private const string QUICKDEPLOYJOBS = "quickdeployjobs";

        private int DoQuickDeployProperty(StringDictionary keyValues, out string output)
        {
            if (!keyValues.ContainsKey("url"))
            {
                throw new InvalidOperationException("The url parameter was not specified.");
            }

            String url = keyValues["url"];

            try
            {
                using (SPSite site = new SPSite(url))
                {
                    using (SPWeb web = site.RootWeb)
                    {
                        if (web.Properties.ContainsKey(QUICKDEPLOYJOBS))
                        {
                            output = string.Format("Current:\r\n{0}", new object[] { web.Properties[QUICKDEPLOYJOBS] });
                            if (keyValues.ContainsKey("clear"))
                            {
                                web.Properties[QUICKDEPLOYJOBS] = null;
                                web.Properties.Update();
                                output += "\r\n\r\nCleared! Don't forget to re-apply the Quick Deploy Settings for this Site Collection.";
                            }
                        }
                        else
                        {
                            output = "The property is not present in this Site Collection";
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw new InvalidOperationException("Error retrieving url '" + url + "'.  Please check the format of your url, and ensure that the site exists.  Details: " + e.Message);
            }

            return 0;
        }
    }
}
